package com.clouddo.admin.service.impl;

import com.clouddo.admin.domain.UserDO;
import com.clouddo.admin.dto.LoginDTO;
import com.clouddo.admin.service.LoginService;
import com.clouddo.admin.service.MenuService;
import com.clouddo.admin.service.TokenService;
import com.clouddo.admin.service.UserService;
import com.clouddo.admin.utils.MD5Utils;
import com.clouddo.admin.vo.LoginVO;
import com.clouddo.common.constants.StatusCode;
import com.clouddo.common.dto.UserToken;
import com.clouddo.common.exception.CustomException;
import com.clouddo.common.utils.JwtUtils;
import com.clouddo.common.utils.R;
import com.clouddo.common.utils.StringUtil;
import com.clouddo.common.vo.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @classDesc: 功能描述:()
 * @author: xinjinlong
 * @date: 2019/1/21 18:32
 * @copyright (C), 2015-2018, 辰森世纪
 * @email: xjl@choicesoft.com.cn
 */
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private MenuService menuService;

    @Override
    public JsonResult<LoginVO> login(LoginDTO loginDTO) {

        //1.根据登录信息获取用户信息
        UserDO userDO = userService.getLoginUser(loginDTO);
        if (userDO == null){
            return JsonResult.getErrorResult(StatusCode.LOGIN_ERROR);
        }

        //2.清空用户权限、菜单相关的缓存信息
        menuService.clearCache(userDO.getUserId());
        return JsonResult.getSuccessResult(getLoginVO(userDO));
    }

    /**
     * 根据用户信息获取登录返回信息
     * @param userDO 用户信息
     * @return
     */
    private LoginVO getLoginVO(UserDO userDO) {
        UserToken userToken = new UserToken(userDO.getUsername(), userDO.getUserId().toString(), userDO.getName());
        return new LoginVO()
                .setToken(JwtUtils.generateToken(userToken))
                .setUser(userDO)
                .setPerms(menuService.PermsByUserId(userDO.getUserId()))
                .setRouter(menuService.RouterDTOsByUserId(userDO.getUserId()));
    }


}
